package com.ruoyi.file.utils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class UrlToMultipartFileUtil {

    /**
     * 将网络文件URL转换为MultipartFile对象
     * @param fileUrl 文件URL
     * @return MultipartFile 对象
     * @throws IOException 如果下载或转换过程中出错
     */
    public static MultipartFile convert(String fileUrl) throws IOException {
        HttpURLConnection connection = null;
        InputStream inputStream = null;

        try {
            // 创建URL对象
            URL url = new URL(fileUrl);
            connection = (HttpURLConnection) url.openConnection();

            // 设置请求参数
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(30000);
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.connect();

            // 检查响应状态
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new IOException("Failed to download file, HTTP response code: " + connection.getResponseCode());
            }

            // 获取文件名
            String fileName = extractFileName(connection, url);

            // 获取内容类型
            String contentType = connection.getContentType();
            if (contentType == null || contentType.isEmpty()) {
                contentType = "application/octet-stream"; // 默认类型
            }

            // 将输入流转换为字节数组
            inputStream = connection.getInputStream();
            byte[] fileBytes = IOUtils.toByteArray(inputStream); // 替代readAllBytes()

            // 创建MultipartFile对象
            return new MockMultipartFile(
                    "file",          // name
                    fileName,        // original filename
                    contentType,     // content type
                    fileBytes        // file content
            );
        } finally {
            // 确保资源关闭
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // ignore
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 从URL或响应头中提取文件名
     */
    private static String extractFileName(HttpURLConnection connection, URL url) {
        // 尝试从Content-Disposition头获取文件名
        String contentDisposition = connection.getHeaderField("Content-Disposition");
        if (contentDisposition != null && contentDisposition.contains("filename=")) {
            String fileName = contentDisposition.split("filename=")[1];
            return fileName.replace("\"", "").replace(";", "").trim();
        }

        // 从URL路径获取文件名
        String path = url.getPath();
        if (path.contains("/")) {
            String tempName = path.substring(path.lastIndexOf('/') + 1);
            if (!tempName.isEmpty()) {
                return tempName.contains("?") ? tempName.split("\\?")[0] : tempName;
            }
        }

        // 生成随机文件名
        return "downloaded_" + UUID.randomUUID().toString().substring(0, 8);
    }

    // 本地测试方法
    public static void main(String[] args) {
        // 测试URL（可以替换为您想测试的图片或文件URL）
        String testUrl = "http://open-mediarecoder.oss-cn-hangzhou.aliyuncs.com/CAPTURE_FILES/174b03759c28486eb22858cf912919dc/lvlian001/FW5810320-2/1747277327000.jpg?Expires=1747284528&OSSAccessKeyId=LTAI4G6HFM3XPqa8rBjxHJRE&Signature=3E8Hczh2qxHhDWxC2IA5UBnFrOs%3D";
//
        System.out.println("开始测试URL转换: " + testUrl);

        try {
            MultipartFile file = convert(testUrl);

            System.out.println("\n转换结果:");
            System.out.println("文件名: " + file.getOriginalFilename());
            System.out.println("文件类型: " + file.getContentType());
            System.out.println("文件大小: " + file.getSize() + " bytes");
            System.out.println("前10字节: " + bytesToHex(file.getBytes(), 10));

            System.out.println("\n测试成功！");
        } catch (Exception e) {
            System.err.println("测试失败:");
            e.printStackTrace();
        }
    }

    // 辅助方法：字节数组转十六进制字符串（用于测试显示）
    private static String bytesToHex(byte[] bytes, int length) {
        if (bytes == null || bytes.length == 0) return "";
        int len = Math.min(bytes.length, length);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            sb.append(String.format("%02X ", bytes[i]));
        }
        return sb.toString().trim();
    }
}